<template>
  <div style="font-family:Simsun">
    <el-card>
      <template #header>
        <h2>流动人口管理</h2>
      </template>
      <el-form inline>
        <el-form-item label="姓名">
          <el-input v-model="queryForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="queryForm.idNumber" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button type="warning" @click="resetList">重置</el-button>
        </el-form-item>
        <el-form-item style="float: right; margin-right:80px">
          <el-button type="primary" @click="openAddMigrantDialog">新增流动人员</el-button>
          <el-button type="danger" @click="deleteMultipleMigrants">删除</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" height="680" stripe border fit style="width: 100%"
        @selection-change="handleSelectionChange" ref="multipleTable">
        <el-table-column type="selection" width="55" />
        <el-table-column label="流动编号" align="center" prop="migrantId" width="90px" />
        <el-table-column label="姓名" align="center" prop="population.name" width="120px" />
        <el-table-column label="性别" align="center" prop="population.gender" width="200px" />
        <el-table-column label="身份证号码" align="center" prop="population.idNumber" width="300px" />
        <el-table-column label="现居住地" align="center" prop="currentAddress" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button size="small" type="primary" @click="viewDetails(scope.row)">详细</el-button>
            <el-button type="success" size="small" @click="editMigrant(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteSingleMigrant(scope.row)">删除</el-button>



          </template>
        </el-table-column>
      </el-table>

      <div class="demo-pagination-block" style="text-align: right;">
        <el-pagination v-model:current-page="queryForm.pageNum" v-model:page-size="queryForm.pageSize" :small="small"
          :disabled="disabled" :background="background" layout="prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
      <!-- 详细信息弹窗 -->
      <el-dialog v-model="detailedInformationDFV" :title="dialogTitle" width="1000px">
        <el-form :model="detailData" label-width="120px">
          <div v-if="mode === 'add'" style="display: flex; align-items: flex-start;">
            <el-form-item label="搜索身份证号" style="flex: 1 0 42%;">
              <el-input v-model="queryForm.idNumber" placeholder="请输入身份证号" />
            </el-form-item>
            <el-button type="primary" @click="searchByIdNumber" style="flex: 1 0 10%; margin-left: 15px">搜索</el-button>
            <el-form-item style="flex: 1 0 27%;">
            </el-form-item>
          </div>
          <div style="display: flex; flex-wrap: wrap;">
            <el-form-item label="姓名*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.name" :disabled="true" />
            </el-form-item>
            <el-form-item label="性别*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.gender" :disabled="true" />
            </el-form-item>
            <el-form-item label="出生日期*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.birthDate" :disabled="true"
                :value="detailData.population.birthDate ? new Date(detailData.population.birthDate).toLocaleDateString() : ''" />
            </el-form-item>
            <el-form-item label="身份证号*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.idNumber" :disabled="true" />
            </el-form-item>
            <el-form-item label="户籍地址*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.householdAddress" :disabled="true" />
            </el-form-item>
            <el-form-item label="民族*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.ethnicity" :disabled="true" />
            </el-form-item>
            <el-form-item label="文化程度*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.educationLevel" :disabled="true" />
            </el-form-item>
            <el-form-item label="是否残疾" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.isDisabled" :disabled="true" />
            </el-form-item>
            <el-form-item label="血型" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.bloodType" :disabled="true" />
            </el-form-item>
            <el-form-item label="兵役状况" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.militaryStatus" :disabled="true" />
            </el-form-item>
            <el-form-item label="婚姻状况" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.maritalStatus" :disabled="true" />
            </el-form-item>
            <el-row>
              <el-form-item label="编号" style="flex: 1 0 33%;">
                <el-input v-model="detailData.migrantId" :disabled="true" />
              </el-form-item>
              <el-form-item label="派出所" style="flex: 1 0 33%;">
                <el-input v-model="detailData.policeStation" :disabled="true" />
              </el-form-item>
              <el-form-item label="业务类别" style="flex: 1 0 33%;">
                <el-input v-model="detailData.businessType" :disabled="true" />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="现居地址*" style="flex: 1 0 33%;">
                <el-input v-model="detailData.currentAddress" :disabled="mode === 'view'" />
              </el-form-item>
              <el-form-item label="居住时间*" style="flex: 1 0 33%;">
                <el-input v-model="detailData.residenceDuration" :disabled="mode === 'view'" />
              </el-form-item>
              <el-form-item label="居住事由" style="flex: 1 0 33%;">
                <el-input v-model="detailData.migrationReason" :disabled="mode === 'view'" maxlength="30" />
              </el-form-item>
            </el-row>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer" style="display: flex; justify-content: flex-end;">
          <el-button v-if="mode === 'add'" @click="saveMigrant">保存</el-button>
          <el-button v-if="mode === 'edit'" @click="saveUpdateMigrant">更新</el-button>
          <el-button @click="detailedInformationDFV = false">关闭</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { getMigrantList } from "../../../api/epgms/migrant/list.js";
import { updateMigrant } from "../../../api/epgms/migrant/update.js";
import { searchPopulationByIdNumber } from "../../../api/epgms/population/search.js";
import { deleteMigrant } from "../../../api/epgms/migrant/delete.js";
import { ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from 'vuex';
import { number } from "echarts";

const queryForm = ref({
  name: '',
  idNumber: '',
  pageNum: 1,
  pageSize: 10
});
const tableData = ref([]);
const total = ref(0);
const small = ref(false);
const background = ref(true);
const disabled = ref(false);
const detailedInformationDFV = ref(false);
const dialogTitle = ref('');
const mode = ref('view'); // 用于区分是新增还是查看
const selectedRows = ref([]); // 存储选中的行
let searchIdNumber = ref('');
const officerInfo = useStore().getters.officerInfo;
const detailData = ref({
  population: {
    name: '',
    gender: '',
    idNumber: '',
    birthDate: '',
    maritalStatus: '',
    educationLevel: '',
    householdAddress: '',
    ethnicity: '',
    isDisabled: '',
    residenceDuration: '',
    bloodType: '',
    militaryStatus: '',
    personId: '',
  },
  migrantId: '',
  migrationReason: '',
  policeStation: '',
  businessType: '',
  currentAddress: '',
  residenceDuration: '',
  policeStationId: '',
});

const openAddMigrantDialog = () => {
  mode.value = 'add';
  dialogTitle.value = '新增流动人口';
  detailedInformationDFV.value = true;
  detailData.value.policeStation = officerInfo.policeStation.name
  clearDetailData();
};
const editMigrant = (row) => {
  mode.value = "edit";
  dialogTitle.value = "编辑流动人员";
  detailData.value = { ...row };
  detailData.value.policeStation = officerInfo.policeStation.name
  detailedInformationDFV.value = true;
};

const viewDetails = (row: any) => {
  mode.value = 'view';
  dialogTitle.value = '流动人口信息';
  detailData.value = row;
  detailData.value.policeStation = officerInfo.policeStation.name
  detailedInformationDFV.value = true;
};

const clearDetailData = () => {
  detailData.value = {
    population: {
      name: '',
      gender: '',
      idNumber: '',
      birthDate: '',
      maritalStatus: '',
      educationLevel: '',
      householdAddress: '',
      ethnicity: '',
      isDisabled: '',
      residenceDuration: '',
      bloodType: '',
      militaryStatus: '',
      personId: '',
    },
    migrantId: '',
    migrationReason: '',
    policeStation: '',
    businessType: '',
    currentAddress: '',
    residenceDuration: '',
    policeStationId: '',
  };
};

const searchByIdNumber = async () => {
  const res = await searchPopulationByIdNumber({
    idNumber: queryForm.value.idNumber,
  });
  if (res.data.code === 2000 && res) {
    const person = res.data.data;
    detailData.value.population.personId = person.personId;
    detailData.value.population.name = person.name;
    detailData.value.population.gender = person.gender;
    detailData.value.population.idNumber = person.idNumber;
    detailData.value.population.birthDate = person.birthDate;
    detailData.value.population.householdAddress = person.household.householdAddress;
    detailData.value.population.ethnicity = person.ethnicity; // Assuming this is mapped correctly
    detailData.value.population.educationLevel = person.educationLevel;
    detailData.value.population.isDisabled = person.isDisabled; // This field is not in the response
    detailData.value.population.residenceDuration = person.residenceDuration; // This field is not in the response
    detailData.value.population.bloodType = person.bloodType; // This field is not in the response
    detailData.value.population.militaryStatus = person.militaryStatus; // This field is not in the response
    detailData.value.population.maritalStatus = person.maritalStatus;
    detailData.value.migrantId = person.personId; // This field is not in the response
    detailData.value.migrationReason = person.migrationReason; // This field is not in the response
    detailData.value.policeStation = officerInfo.policeStation.name; // This field is not in the response
    detailData.value.businessType = '流动人口'; // This field is not in the response
    detailData.value.currentAddress = person.currentAddress;
  } else {
    console.error("Failed to fetch data or no matching record found");
  }
};


const saveMigrant = async () => {
  try {
    const res = await updateMigrant({
      personId: detailData.value.population.personId,
      currentAddress: detailData.value.currentAddress,
      residenceDuration: detailData.value.residenceDuration,
      migrationReason: detailData.value.migrationReason,
      policeStationId: officerInfo.policeStation.stationId
    }); // 调用后端API保存流动人口信息

    if (res.data.code === 2000) {
      console.log('成功保存流动人口信息:', detailData.value);
      detailedInformationDFV.value = false;
      await fetchData(); // 保存成功后刷新列表数据
      ElMessage({
        message: '保存成功！',
        type: 'success',
      })
    } else {
      console.error('保存失败:', res.data.message || '未知错误')
      ElMessage.error('保存失败！')
    }
  } catch (error) {
    console.error('保存失败:', error.message || '未知错误');
    ElMessage.error('保存失败！')
  }
};
const saveUpdateMigrant = async () => {
  try {
    console.log("-----------------------------------wsq")
    console.log(detailData.value.currentAddress)
    const res = await updateMigrant({
      personId: detailData.value.population.personId,
      currentAddress: detailData.value.currentAddress,
      residenceDuration: detailData.value.residenceDuration,
      migrationReason: detailData.value.migrationReason,
      policeStationId: officerInfo.policeStation.stationId,
      migrantId: detailData.value.migrantId
    }); // 调用后端API保存流动人口信息
    if (res.data.code === 2000) {
      console.log('成功保存流动人口信息:', detailData.value);
      detailedInformationDFV.value = false;
      await fetchData(); // 保存成功后刷新列表数据
      ElMessage({
        message: '更新成功！',
        type: 'success',
      })
    } else {
      console.error('更新失败:', res.data.message || '未知错误')
      ElMessage.error('更新失败！')
    }
  } catch (error) {
    console.error('更新失败:', error.message || '未知错误');
    ElMessage.error('更新失败！')
  }
};


// 删除单个流动人口
const deleteSingleMigrant = async (row: any) => {
  ElMessageBox.confirm(
    '您确定要删除这条数据?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        const res = await deleteMigrant([row.migrantId]); // 调用后端API删除流动人口信息

        if (res.every(r => r.data.code === 2000)) {
          console.log('成功删除流动人口信息:', row);
          await fetchData(); // 删除成功后刷新列表数据
          ElMessage({
            message: '删除成功！',
            type: 'success',
          })
        } else {
          console.error('删除失败:', res[0].data.message || '未知错误');
          ElMessage.error('删除失败！')
        }
      } catch (error) {
        console.error('删除失败:', error.message || '未知错误');
        ElMessage.error('删除失败！')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })

};

const handleSelectionChange = (val) => {
  selectedRows.value = val;
};
// 批量删除流动人口
const deleteMultipleMigrants = async () => {

  ElMessageBox.confirm(
    '您确定要删除这几条数据?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      if (selectedRows.value.length === 0) {
        ElMessage.error('请选择需要删除的内容！')
        return;
      }
      const ids = selectedRows.value.map(row => row.migrantId);
      const res = await deleteMigrant(ids);

      if (res.every(r => r.data.code === 2000)) {
        console.log('成功批量删除流动人口信息:', ids);
        await fetchData(); // 删除成功后刷新列表数据
        ElMessage({
          message: '删除成功！',
          type: 'success',
        })
      } else {
        console.error('批量删除失败:', res[0].data.message || '未知错误');
        ElMessage.error('删除失败！')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
};
const handleSizeChange = (val: number) => {
  queryForm.value.pageSize = val;
  fetchData();
};

const handleCurrentChange = (val: number) => {
  queryForm.value.pageNum = val;
  fetchData();
};

const search = () => {
  queryForm.value.pageNum = 1; // 重置为第一页
  fetchData();
};
const resetList = () => {
  queryForm.value.name = ""
  queryForm.value.idNumber = ""
  queryForm.value.pageNum = 1
  queryForm.value.pageSize = 10
  fetchData()
}
const fetchData = async () => {
  try {
    const res = await getMigrantList({
      name: queryForm.value.name,
      idNumber: queryForm.value.idNumber,
      pageNum: queryForm.value.pageNum,
      pageSize: queryForm.value.pageSize
    });

    console.log('API response:', res); // Debugging: log the response

    if (res && res.data.code === 2000 && res.data) {
      tableData.value = res.data.data;
      total.value = res.data.total;
      console.log('Fetched data:', tableData.value); // Debugging: log the fetched data
    } else {
      console.error("Failed to fetch data or data format is incorrect");
    }
  } catch (error) {
    console.error("Error fetching data:", error);
  }
};

fetchData();
</script>

<style scoped>
.demo-pagination-block {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

::v-deep .el-form-item__label {
  color: #000000;
  font-size: 16px;
}

::v-deep .el-button el-button--primary {
  align-items: center;
}
</style>
